package com.tsunami.message.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsunami.message.common.Constant;
import com.tsunami.message.entity.MsgLog;
import com.tsunami.message.mapper.MsgLogMapper;
import com.tsunami.message.service.IMsgLogService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author lx
 * @date 2024-09-19
 */
@Service
public class MsgLogServiceImpl extends ServiceImpl<MsgLogMapper, MsgLog> implements IMsgLogService {
    @Override
    public void insert(MsgLog msgLog) {
        super.save(msgLog);
    }

    @Override
    public void updateStatus(String msgId, Integer status, String result) {
        LambdaQueryWrapper<MsgLog> param = new LambdaQueryWrapper<>();
        param.eq(MsgLog::getMsgId,msgId);
        MsgLog msgLog = getOne(param);
        msgLog.setStatus(status);
        msgLog.setResult(result);
        msgLog.setUpdateTime(LocalDateTime.now());
        super.updateById(msgLog);
    }

    @Override
    public List<MsgLog> selectFailMsg() {
        LambdaQueryWrapper<MsgLog> param = new LambdaQueryWrapper<>();
        param.eq(MsgLog::getStatus, Constant.FAIL);
        param.eq(MsgLog::getNextTryTime, LocalDateTime.now());
        return list(param);
    }

    @Override
    public void updateTryCount(MsgLog msgLog) {
        LambdaQueryWrapper<MsgLog> param = new LambdaQueryWrapper<>();
        param.eq(MsgLog::getMsgId,msgLog.getMsgId());
        MsgLog entity = getOne(param);
        entity.setTryCount(entity.getTryCount()+1);
        entity.setUpdateTime(LocalDateTime.now());
        super.updateById(entity);
    }

    @Override
    public MsgLog selectByPrimaryKey(String msgId) {
        LambdaQueryWrapper<MsgLog> param = new LambdaQueryWrapper<>();
        param.eq(MsgLog::getMsgId,msgId);
        return getOne(param);
    }

    @Override
    public void updateNextTryTime(String msgId, int count) {
        MsgLog msgLog = selectByPrimaryKey(msgId);
        msgLog.setNextTryTime(LocalDateTime.now().plusMinutes(count));
        super.updateById(msgLog);
    }
}
